<template>
  <div class="announcement-messages-container">
    <div class="main-content">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-left">
          <h1 class="page-title">
            <el-icon><Bell /></el-icon>
            消息中心
          </h1>
          <p class="page-description">查看所有公告信息</p>
        </div>
        <div class="header-right">
          <el-badge
            :value="unreadCount"
            :hidden="unreadCount === 0"
            type="danger"
          >
            <el-button type="primary" @click="handleMarkAllAsRead">
              <el-icon><Check /></el-icon>
              全部已读
            </el-button>
          </el-badge>
        </div>
      </div>

      <!-- 筛选和搜索 -->
      <el-card class="filter-card" shadow="never">
        <el-form :model="queryParams" label-width="auto" class="filter-form">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6">
              <el-form-item label="阅读状态">
                <el-select
                  v-model="queryParams.readStatus"
                  placeholder="全部"
                  clearable
                  @change="handleQuery"
                >
                  <el-option label="未读" :value="0" />
                  <el-option label="已读" :value="1" />
                  <el-option label="已忽略" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6">
              <el-form-item label="公告类型">
                <el-select
                  v-model="queryParams.type"
                  placeholder="全部"
                  clearable
                  @change="handleQuery"
                >
                  <el-option label="系统公告" :value="1" />
                  <el-option label="活动公告" :value="2" />
                  <el-option label="维护公告" :value="3" />
                  <el-option label="其他" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6">
              <el-form-item label="公告级别">
                <el-select
                  v-model="queryParams.level"
                  placeholder="全部"
                  clearable
                  @change="handleQuery"
                >
                  <el-option label="普通" :value="1" />
                  <el-option label="重要" :value="2" />
                  <el-option label="紧急" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6">
              <el-form-item label-width="0">
                <el-button type="primary" @click="handleQuery">
                  <el-icon><Search /></el-icon>
                  查询
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 公告列表 -->
      <el-card v-loading="loading" class="list-card" shadow="never">
        <div
          v-if="announcementList.records.length > 0"
          class="announcements-list"
        >
          <div
            v-for="announcement in announcementList.records"
            :key="announcement.id"
            class="announcement-item"
            :class="{
              'is-unread': announcement.readStatus === null,
              'is-ignored': announcement.ignored
            }"
            @click="handleViewDetail(announcement)"
          >
            <!-- 公告头部 -->
            <div class="item-header">
              <div class="header-left">
                <el-tag
                  :type="utils.getLevelInfo(announcement.level).tagType"
                  size="small"
                  class="level-tag"
                >
                  {{ announcement.levelName }}
                </el-tag>
                <el-tag
                  :type="utils.getTypeInfo(announcement.type).tagType"
                  size="small"
                  effect="plain"
                >
                  <el-icon>
                    <component
                      :is="utils.getTypeInfo(announcement.type).icon"
                    />
                  </el-icon>
                  {{ announcement.typeName }}
                </el-tag>
                <el-tag v-if="announcement.isTop" type="danger" size="small">
                  置顶
                </el-tag>
                <el-tag
                  :type="
                    utils.getReadStatusInfo(announcement.readStatus).tagType
                  "
                  size="small"
                >
                  {{ utils.getReadStatusInfo(announcement.readStatus).label }}
                </el-tag>
              </div>
              <div class="header-right">
                <span class="announcement-time">
                  {{ utils.formatTime(announcement.publishTime) }}
                </span>
              </div>
            </div>

            <!-- 公告标题 -->
            <div class="item-title">
              {{ announcement.title }}
            </div>

            <!-- 公告内容预览 -->
            <div class="item-content">
              {{ utils.truncateContent(announcement.content, 150) }}
            </div>

            <!-- 公告元信息 -->
            <div class="item-meta">
              <span class="meta-item">
                <el-icon><View /></el-icon>
                {{ utils.formatNumber(announcement.viewCount) }} 次浏览
              </span>
              <span v-if="announcement.readTime" class="meta-item">
                <el-icon><Clock /></el-icon>
                阅读于 {{ utils.formatTime(announcement.readTime) }}
              </span>
            </div>

            <!-- 操作按钮 -->
            <div class="item-actions" @click.stop>
              <el-button
                v-if="announcement.readStatus === null"
                size="small"
                type="primary"
                plain
                @click="handleMarkAsRead(announcement)"
              >
                <el-icon><Check /></el-icon>
                标记已读
              </el-button>
              <el-button
                v-if="announcement.ignored"
                size="small"
                type="info"
                plain
                @click="handleUnignore(announcement)"
              >
                <el-icon><RefreshLeft /></el-icon>
                取消忽略
              </el-button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty v-else description="暂无公告" />

        <!-- 分页 -->
        <div v-if="announcementList.total > 0" class="pagination-wrapper">
          <el-pagination
            v-model:current-page="queryParams.current"
            v-model:page-size="queryParams.size"
            :total="announcementList.total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            background
            @current-change="handleQuery"
            @size-change="handleQuery"
          />
        </div>
      </el-card>
    </div>

    <!-- 公告详情对话框 -->
    <AnnouncementDetailDialog
      v-model:visible="detailDialogVisible"
      :announcement-id="selectedAnnouncementId"
      @read="handleAnnouncementRead"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Bell,
  Check,
  Search,
  Refresh,
  View,
  Clock,
  RefreshLeft
} from "@element-plus/icons-vue";
import {
  getMessageCenterAnnouncementsApi,
  markAnnouncementAsReadApi,
  markAllAnnouncementsAsReadApi,
  unignoreAnnouncementApi,
  UserAnnouncementUtils,
  type MessageCenterAnnouncementInfo,
  type PageResponse,
  type GetMessageCenterAnnouncementsParams
} from "@/api/user-announcement";
import { notificationService } from "@/services/notificationService";
import AnnouncementDetailDialog from "./components/AnnouncementDetailDialog.vue";

// 工具类
const utils = UserAnnouncementUtils;

// 状态
const loading = ref(false);
const detailDialogVisible = ref(false);
const selectedAnnouncementId = ref<number>();

// 使用单例服务获取公告未读数
const statsRef = notificationService.getStatsRef();
const unreadCount = computed(() => {
  return (
    statsRef.value?.unreadAnnouncementCount ||
    statsRef.value?.announcementUnread ||
    0
  );
});

// 查询参数
const queryParams = ref<GetMessageCenterAnnouncementsParams>({
  current: 1,
  size: 10,
  type: undefined,
  level: undefined,
  readStatus: undefined
});

// 公告列表
const announcementList = ref<PageResponse<MessageCenterAnnouncementInfo>>({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 0
});

// 加载公告列表
const loadAnnouncementList = async () => {
  loading.value = true;
  try {
    const response = await getMessageCenterAnnouncementsApi(queryParams.value);
    if (response.code === 200 && response.data) {
      announcementList.value = response.data;
    } else {
      ElMessage.error(response.message || "加载公告列表失败");
    }
  } catch (error: any) {
    console.error("加载公告列表失败:", error);
    ElMessage.error(utils.formatErrorMessage(error));
  } finally {
    loading.value = false;
  }
};

// 加载未读数量
const loadUnreadCount = async () => {
  await notificationService.loadStats();
};

// 查询
const handleQuery = () => {
  queryParams.value.current = 1;
  loadAnnouncementList();
};

// 重置
const handleReset = () => {
  queryParams.value = {
    current: 1,
    size: 10,
    type: undefined,
    level: undefined,
    readStatus: undefined
  };
  loadAnnouncementList();
};

// 查看详情
const handleViewDetail = (announcement: MessageCenterAnnouncementInfo) => {
  selectedAnnouncementId.value = announcement.id;
  detailDialogVisible.value = true;
};

// 标记已读
const handleMarkAsRead = async (
  announcement: MessageCenterAnnouncementInfo
) => {
  try {
    const response = await markAnnouncementAsReadApi(announcement.id);
    if (response.code === 200) {
      ElMessage.success("已标记为已读");
      announcement.read = true;
      announcement.readStatus = 1;
      announcement.readStatusName = "已读";
      loadUnreadCount();
    } else {
      ElMessage.error(response.message || "标记已读失败");
    }
  } catch (error: any) {
    console.error("标记已读失败:", error);
    ElMessage.error(utils.formatErrorMessage(error));
  }
};

// 全部已读
const handleMarkAllAsRead = async () => {
  if (unreadCount.value === 0) {
    ElMessage.info("没有未读公告");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确认将所有 ${unreadCount.value} 条未读公告标记为已读？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await markAllAnnouncementsAsReadApi();
    if (response.code === 200) {
      ElMessage.success("已标记所有公告为已读");
      loadAnnouncementList();
      loadUnreadCount();
    } else {
      ElMessage.error(response.message || "标记全部已读失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("标记全部已读失败:", error);
      ElMessage.error(utils.formatErrorMessage(error));
    }
  }
};

// 取消忽略
const handleUnignore = async (announcement: MessageCenterAnnouncementInfo) => {
  try {
    const response = await unignoreAnnouncementApi(announcement.id);
    if (response.code === 200) {
      ElMessage.success("已取消忽略");
      announcement.ignored = false;
      announcement.readStatus = null;
      announcement.readStatusName = "未读";
      loadUnreadCount();
    } else {
      ElMessage.error(response.message || "取消忽略失败");
    }
  } catch (error: any) {
    console.error("取消忽略失败:", error);
    ElMessage.error(utils.formatErrorMessage(error));
  }
};

// 公告已读回调
const handleAnnouncementRead = (id: number) => {
  const announcement = announcementList.value.records.find(
    item => item.id === id
  );
  if (announcement) {
    announcement.read = true;
    announcement.readStatus = 1;
    announcement.readStatusName = "已读";
  }
  loadUnreadCount();
};

// 组件挂载
onMounted(() => {
  loadAnnouncementList();
  loadUnreadCount();
});
</script>

<style scoped lang="scss">
/* 响应式设计 */
@media (width <= 768px) {
  .announcement-messages-container {
    padding: 12px;

    .main-content {
      .page-header {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
        padding: 16px;

        .header-left {
          .page-title {
            font-size: 24px;

            .el-icon {
              font-size: 28px;
            }
          }
        }

        .header-right {
          width: 100%;

          .el-button {
            width: 100%;
          }
        }
      }

      .filter-card {
        :deep(.el-card__body) {
          padding: 16px;
        }

        .filter-form {
          .el-col {
            margin-bottom: 12px;

            &:last-child {
              margin-bottom: 0;
            }
          }

          .el-button {
            width: 100%;
          }
        }
      }

      .list-card {
        :deep(.el-card__body) {
          padding: 12px;
        }

        .announcements-list {
          .announcement-item {
            padding: 16px;

            .item-header {
              flex-direction: column;
              gap: 8px;
              align-items: flex-start;

              .header-right {
                width: 100%;

                .announcement-time {
                  font-size: 12px;
                }
              }
            }

            .item-title {
              font-size: 16px;
            }

            .item-content {
              font-size: 13px;
            }

            .item-meta {
              gap: 12px;
              font-size: 12px;
            }

            .item-actions {
              .el-button {
                flex: 1;
              }
            }
          }
        }

        .pagination-wrapper {
          :deep(.el-pagination) {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            justify-content: center;

            .el-pagination__total,
            .el-pagination__sizes,
            .el-pagination__jump {
              margin: 0;
            }
          }
        }
      }
    }
  }
}

.announcement-messages-container {
  min-height: 100vh;
  padding: 20px;
  background: #f5f7fa;

  .main-content {
    max-width: 1200px;
    margin: 0 auto;

    .page-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 24px;
      margin-bottom: 24px;
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 12px rgb(0 0 0 / 5%);

      .header-left {
        .page-title {
          display: flex;
          gap: 12px;
          align-items: center;
          margin: 0 0 8px;
          font-size: 28px;
          font-weight: 600;
          color: #303133;

          .el-icon {
            font-size: 32px;
            color: #0ea5e9;
          }
        }

        .page-description {
          margin: 0;
          font-size: 14px;
          color: #909399;
        }
      }

      .header-right {
        .el-badge {
          :deep(.el-badge__content) {
            font-size: 12px;
          }
        }
      }
    }

    .filter-card {
      margin-bottom: 20px;

      .filter-form {
        .el-form-item {
          margin-bottom: 0;
        }
      }
    }

    .list-card {
      .announcements-list {
        .announcement-item {
          padding: 20px;
          margin-bottom: 16px;
          cursor: pointer;
          background: #fff;
          border: 1px solid #e4e7ed;
          border-radius: 12px;
          transition: all 0.3s ease;

          &:hover {
            box-shadow: 0 4px 16px rgb(0 0 0 / 10%);
            transform: translateY(-2px);
          }

          &.is-unread {
            background: linear-gradient(
              135deg,
              rgb(224 242 255 / 50%) 0%,
              rgb(186 230 255 / 50%) 100%
            );
            border-color: #7dd3fc;
          }

          &.is-ignored {
            opacity: 0.7;
          }

          &:last-child {
            margin-bottom: 0;
          }

          .item-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;

            .header-left {
              display: flex;
              flex-wrap: wrap;
              gap: 8px;
              align-items: center;

              .el-tag {
                display: inline-flex !important;
                gap: 4px;
                align-items: center !important;
                justify-content: center;
                height: 24px;
                padding: 0 8px !important;
                font-size: 13px !important;
                font-weight: 500 !important;
                line-height: 1 !important;

                :deep(span) {
                  display: flex;
                  align-items: center;
                  font-size: 13px !important;
                  font-weight: 500 !important;
                  line-height: 1 !important;
                }

                .el-icon {
                  display: flex;
                  align-items: center;
                  margin: 0;
                  font-size: 13px !important;
                }
              }
            }

            .header-right {
              .announcement-time {
                font-size: 13px;
                color: #909399;
                white-space: nowrap;
              }
            }
          }

          .item-title {
            margin-bottom: 8px;
            font-size: 18px;
            font-weight: 600;
            line-height: 1.5;
            color: #0c4a6e;
          }

          .item-content {
            margin-bottom: 12px;
            font-size: 14px;
            line-height: 1.6;
            color: #475569;
          }

          .item-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            margin-bottom: 12px;
            font-size: 13px;
            color: #909399;

            .meta-item {
              display: flex;
              gap: 4px;
              align-items: center;

              .el-icon {
                font-size: 14px;
              }
            }
          }

          .item-actions {
            display: flex;
            gap: 8px;
          }
        }
      }

      .pagination-wrapper {
        display: flex;
        justify-content: center;
        margin-top: 24px;
      }
    }
  }
}
</style>
